import { BadRequestException, ValidationError, ValidationPipe } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { NestFactory, Reflector } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'
import { HttpExceptionFilter } from './config/filter/HttpExceptionFilter'
import { TransformInterceptor } from './config/interceptor/TransformInterceptor'
import { ConfigurationKeys } from './config/resources'

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  )

  // const app = await NestFactory.create(AppModule)

  app.enableCors()
  app.useGlobalFilters(new HttpExceptionFilter())
  app.useGlobalInterceptors(new TransformInterceptor(new Reflector()))


  function getSafeFirstErrorMessage(errors: ValidationError[]): string {
    if (!errors || errors.length === 0) {
      return 'Validation failed'
    }

    const firstError = errors[0]

    // 确保 constraints 存在且是对象
    if (firstError.constraints && typeof firstError.constraints === 'object') {
      const constraintValues = Object.values(firstError.constraints)
      if (constraintValues.length > 0 && constraintValues[0]) {
        return constraintValues[0] as string
      }
    }

    // 尝试从子错误中获取信息
    if (firstError.children && firstError.children.length > 0) {
      return getSafeFirstErrorMessage(firstError.children)
    }

    // 回退错误信息
    return `Validation failed for field '${firstError.property}'`
  }
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true,
    forbidNonWhitelisted: true,
    exceptionFactory: (errors: ValidationError[]) => {
      // 使用安全的方法获取第一个错误
      const firstErrorMessage = getSafeFirstErrorMessage(errors)
      return new BadRequestException(firstErrorMessage)
    }
  }))



  const config = app.get(ConfigService<ConfigurationKeys>)
  const PORT = config.get('server.port')

  await app.listen(PORT, '0.0.0.0')

  console.log(`http://localhost:${PORT}`)
}


bootstrap()
